import React, { useEffect, useState, useCallback } from 'react';
import { Input, Button } from 'antd';
import { connect } from 'dva';
import styles from './index.less';

const SelectInput = ({ value, onChange = () => {}, dispatch }) => {
  const [data, setData] = useState('');
  const [list, setList] = useState(null);
  const [show, showList] = useState(false);
  useEffect(() => {
    setData(value);
    return () => {
      setData('');
    };
  }, [value]);
  useEffect(() => {
    dispatch({
      type: `$request/post`,
      payload: {
        url: '/api/project/report/v1/project/build/query',
        data: { page: 0, size: 40 },
      },
    }).then(res => {
      let list = res.map(item => ({ label: item.name, value: item.uuid }));
      setList(list);
    });
  }, []);

  const inputChange = value => {
    setData(value);
    onChange(value, '');
  };

  const selectChange = data => {
    setData(data.label);
    onChange(data.label, data.value);
  };

  const onBlur = () => {
    setTimeout(() => {
      showList(false);
    }, 500);
  };
  return (
    <div
      className={styles.container}
      onBlur={onBlur}
      onFocus={() => showList(true)}
    >
      <Input value={data} onChange={e => inputChange(e.target.value)}></Input>
      {show && list && list.length ? (
        <div className={styles.list}>
          {list &&
            list.map((item, index) => (
              <div
                key={index}
                className={styles.item}
                onClick={() => selectChange(item)}
              >
                {item.label}
              </div>
            ))}
        </div>
      ) : (
        ''
      )}
    </div>
  );
};

export default connect(state => state.base)(SelectInput);
